import {Component, OnDestroy, OnInit} from '@angular/core';
import {TableUtil} from '../../../util/table-util';
import {MsgConstants} from '../../../constants/constants';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {MsgResult} from '../../../models/msg-result';
import {PageSubject} from '../../../util/page-subject';
import {Observable} from 'rxjs/Observable';
import {ActivatedRoute, Router} from '@angular/router';
import {ResponseUtil} from '../../../util/response-util';
import {DaChartTitle, DaFactorName} from '../da-constants';
import {DaOCECService} from './da-ocec.service';

declare var $;
declare var moment;
declare var echarts;

@Component({
  selector: 'app-da-ocec',
  templateUrl: './da-ocec.component.html',
  styleUrls: ['./da-ocec.component.css']
})
export class DaOCECComponent implements OnInit, OnDestroy {
  config;
  pointType = 'skyEyeSite'; // 点位类型
  factor = 'PM2_5';
  timeDataType = 'hourData';
  siteCode = '';
  rangeCode = '';
  siteArr: Array<any> = [];
  nationCode = '';
  chartObj: any;
  typePieObj: any;
  chartOption: object;
  colorArr: Array<any> = [];
  isLoading = true;
  resizeEnent: any;
  timeDataArr: Array<any> = [];
  table: any;
  startDate = new Date(moment().subtract(1, 'w').format('YYYY/MM/DD HH:00'));
  endDate =  new Date();
  /**
   * 禁用日期数组
   * @type {any[]}
   */
  disabledDate: Array<any> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private dialogService: OneDialogService,
    private response: ResponseUtil,
    private tableUtil: TableUtil,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private ocecService: DaOCECService
  ) { }

  ngOnInit() {
    this.pushPage();
    this.screenChange();
    this.initData();
    this.getSiteData();
  }
  ngOnDestroy () {
    this.destroyResize();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('水溶性离子分析', '');
    this.pageSubject.pushPage('有机碳/元素碳分析', '查询');
  }

  initData = () => {
    $('#ocecChart').css({ 'height': $(window.innerHeight)[0] - 230 + 'px'});
    this.timeDataArr = [{name: '小时', dataType: 'hourData'}, { name: '日', dataType: 'dayData'}, {name: '周', dataType: 'weekData'}];
    this.chartObj = echarts.init(document.getElementById('ocecChart'));
    // this.typePieObj = echarts.init(document.getElementById('typePie'));
    this.colorArr = [
      '#000000', '#34E52B', '#FACC14', '#223273'];
    const chartList = {
      'siteName': '河南省站',
      'nameList': [
        'EC',
        'OC'
      ],
      'factorNameList': [
        'OC/EC',
        'PM2.5'
      ],
      'timeList': [
        '2018-04-17 12:00',
        '2018-04-17 16:00',
        '2018-04-17 20:00',
        '2018-04-18 00:00',
        '2018-04-18 04:00',
        '2018-04-18 08:00',
        '2018-04-18 12:00',
        '2018-04-18 16:00',
        '2018-04-18 20:00',
        '2018-04-19 00:00',
        '2018-04-19 04:00',
        '2018-04-19 08:00',
        '2018-04-19 12:00',
        '2018-04-19 16:00',
        '2018-04-19 20:00',
        '2018-04-20 00:00',
        '2018-04-20 04:00',
        '2018-04-20 08:00',
        '2018-04-20 12:00',
        '2018-04-20 16:00'
      ],
      'dataList': [
        [
          298,
          278,
          39,
          102,
          228,
          33,
          91,
          99,
          17,
          34,
          109,
          95,
          26,
          190,
          8,
          249,
          13,
          266,
          208,
          185
        ],
        [
          188,
          129,
          236,
          109,
          226,
          157,
          48,
          216,
          174,
          285,
          122,
          89,
          110,
          168,
          69,
          250,
          203,
          100,
          205,
          119
        ]
      ],
      'factorDataList': [
        [
          217,
          253,
          269,
          149,
          246,
          211,
          171,
          271,
          291,
          235,
          172,
          181,
          298,
          189,
          170,
          150,
          149,
          202,
          112,
          251
        ],
        [
          188,
          129,
          236,
          109,
          226,
          157,
          48,
          216,
          174,
          285,
          122,
          89,
          110,
          168,
          69,
          250,
          203,
          100,
          205,
          119
        ]
      ]
    };
    // this.chartRender(chartList);
  };
  /**
   * 屏幕大小改变
   */
  screenChange() {
    this.resizeEnent = Observable.fromEvent(window, 'resize')
      .debounceTime(100) // 以免频繁处理
      .subscribe((event) => {
        this.chartObj.getDom().style.height = $(window.innerHeight)[0] - 230 + 'px';
        // 这里处理页面变化时的操作
        this.chartObj.resize();
      });
  }
  /**
   * 取消监听屏幕变化
   * */
  destroyResize() {
    this.resizeEnent.unsubscribe();
  }
  search() {
    if (this.startDate > this.endDate) {
      this.dialogService.info('开始时间大于结束时间，请重新选择');
    } else {
      this.isLoading = true;
      this.getOcecData();
    }
  }
  /**
   * 图表
   * @param chartList
   */
  chartRender(chartList) {
    const compareChart = this.chartObj;
    const dataList = [];
    const ocDataList = [];
    let yMaxData = 0;
    let ocMaxData = 0;
    if (chartList.dataList.length > 0) {
      chartList.dataList.forEach((data, i) => {
        if (chartList.nameList[i] === 'PM₂.₅') {
          if (data.length > 0) {
            data.forEach((val) => {
              if (!isNaN(val)) {
                dataList.push(val);
              }
            });
          }
        } else {
          if (data.length > 0) {
            data.forEach((val) => {
              if (!isNaN(val)) {
                ocDataList.push(val);
              }
            });
          }
        }
      })
    }
    if (dataList.length > 0) {
      yMaxData = Math.ceil(Math.max(...dataList) * 0.5) ;
    }
    if (ocDataList.length > 0) {
      ocMaxData = Math.ceil(Math.max(...ocDataList) ) ;
    }
    // 图表配置信息
    const option: any = {
      tooltip: {
        trigger: 'axis'
      },
      title: [{
        left: 'center',
        text: DaChartTitle.daOcecTitle
      }],
      toolbox: {
        right: '30',
        feature: {
          saveAsImage: {}
        }
      },
      dataZoom: [
        // {
        //   type: 'slider',
        //   show: true,
        //   xAxisIndex: [0]
        // },
        {
          type: 'inside',
          xAxisIndex: [0]
        }
      ],
      legend: {
        bottom: 40,
        left: 'center',
        width: '80%',
        data: []
      },
      grid: [{
        top: 60,
        bottom: 110
      }],
      color: this.colorArr,
      xAxis: [
        {
          type: 'category',
          nameGap: '20',
          // name: '日期',
          nameLocation: 'start',
          // boundaryGap: false,
          data: chartList.timeList,
          axisLabel: {
            // rotate: 45,
            color: '#000',
            formatter: (value, index) => {
              // 格式化
              const h = moment(value).format('H:00');
              if (this.timeDataType === 'hourData') {
                return moment(value).format('M月D日 ')  + '\n' + h;
              } else if (this.timeDataType === 'dayData')  {
                return moment(value).format('M月D日 ')
              } else if (this.timeDataType === 'weekData')  {
                return moment(value).format('M月D日')
              } else if (this.timeDataType === 'yearData')  {
                return moment(value).format('YYYY年 ')
              }
            }
          }
        }
      ],
      yAxis: [
        {
          name: 'μg/m³',
          type: 'value',
          splitLine: {
            show: false
          }
        }, {
          name: 'μg/m³',
          type: 'value',
          splitLine: {
            show: false
          }
        }
      ],
      series: [

      ]
    };
    if (yMaxData && yMaxData > ocMaxData) {
       option.yAxis[0].max = yMaxData;
    }
    const seriesObj = [];
    const nameArr = [];
    chartList.nameList.forEach((name, i) => {
      const showName = DaFactorName[name] || name;
      nameArr.push(showName);
      if (name === 'OC' || name === 'EC') {
        seriesObj.push({
          type: 'bar',
          stack: '总量',
          smooth: true,
          yAxisIndex: 0,
          barMaxWidth: 40,
          name: showName,
          data: chartList.dataList[i]
        })
      } else if (name === 'OC/EC' || name === 'PM₂.₅') {
        seriesObj.push({
          type: 'line',
          smooth: true,
          yAxisIndex: name === 'OC/EC' ? 0 : 1,
          name: showName,
          data: chartList.dataList[i]
        })
      }

    });
    option.series = seriesObj;
    option.legend.data = nameArr;
    console.log(option);
    compareChart.setOption(option, {notMerge: true});
  }
  /**
   * 时间类型切换
   * @param timeDataType
   */
  timeDataChange(timeDataType) {
    if (this.timeDataType === timeDataType) {
      return false;
    }
    this.timeDataType = timeDataType;
    this.changeStartAndEndDate();
    this.search();
  }
  startValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.startDate = null;
    //   this.dialogService.info('开始时间大于结束时间')
    // }
  };
  endValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.endDate = null;
    //   this.dialogService.info('结束时间小于开始时间')
    // }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= startValue.getTime()  && startValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime() || !isInRange;
    } else {
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startDateTime =  new Date(moment(this.startDate).format('YYYY/MM/DD')).getTime();
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= endValue.getTime()  && endValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime || !isInRange;
    } else {
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime;
    }
  };
  get showTimeParams() {
    if (this.timeDataType === 'hourData') {
      return {
        nzFormat: 'HH'
      }
    } else {
      return false;
    }
  }
  /**
   * 获取站点数据
   */
  getSiteData = () => {
    this.ocecService.getSiteData().subscribe(
      result => this.responseUtil.success(result, this.progressD),
      error => this.responseUtil.error(error)
    )
  };
  progressD = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.siteArr = result.data;
        this.siteCode = this.siteArr[0].SITECODE;
        this.rangeCode = this.siteArr[0].RANGECODE;
        this.changeSite(false);
        this.getOcecData();
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  changeSite = (isOpen) => {
    if (!isOpen) {
      if (this.rangeCode) {
        this.disabledDate = [];
        let site;
        this.siteArr.every((val) => {
          if (val.RANGECODE === this.rangeCode) {
            this.siteCode = val.SITECODE;
            site = val;
            return false
          } else {
            return true
          }
        });
        if (site.DATESTR && typeof site.DATESTR === 'string' ) {
          const dateArr = site.DATESTR.split(';');
          if (dateArr.length > 0) {
            dateArr.forEach((val) => {
              const singleDateArr = val.split(',');
              this.disabledDate.push({startDate: singleDateArr[0], endDate: singleDateArr[1]})
            });
            this.changeStartAndEndDate();
          }
        }
      } else {
        this.disabledDate = [];
      }
    }
  };
  /**
   * 修改开始结束时间
   */
  changeStartAndEndDate = () => {
    if (this.disabledDate.length > 0) {
      const dateLength = this.disabledDate.length;
      const dateObj = this.disabledDate[dateLength - 1];
      const startTime = new Date(moment(dateObj.startDate).format('YYYY/MM/DD 00:00:00'));
      const endTime = new Date(moment(dateObj.endDate).format('YYYY/MM/DD 00:00:00'));
      const nowDate =  new Date(moment().format('YYYY/MM/DD 00:00:00'));
      const nowDateIsInRange = startTime.getTime() < nowDate.getTime()  && nowDate.getTime() <= endTime.getTime();
      if (nowDateIsInRange) {
        this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        let startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          startDate = new Date(moment().subtract('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          startDate = new Date(moment().subtract('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          startDate = new Date(moment().subtract('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        const startDateIsInRange = startTime.getTime() < startDate.getTime()  && startDate.getTime() < endTime.getTime();
        if (startDateIsInRange) {
          this.startDate = startDate;
        } else {
          this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        }
      } else {
        this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        let endDate = new Date(moment(dateObj.endDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        if (endDate.getTime() > new Date().getTime()) {
          this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        } else {
          this.endDate = endDate;
        }
      }
    }
  };

  /**
   * 获取图表数据
   */
  getOcecData() {
    const dataObj = {
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      startTime : this.startDate ? moment(this.startDate).format('YYYY-MM-DD HH:00:00') : '',
      endTime : this.endDate ? moment(this.endDate).format('YYYY-MM-DD HH:00:00') : ''
    };
    this.ocecService.getOcecData(dataObj).subscribe(
      result => this.response.success(result, this.handleInodata),
      error => this.response.error(error)
    );
  }
  handleInodata = (result: MsgResult) => {
    this.isLoading = false;
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data) {
        this.chartRender(result.data);
      } else {
        this.chartRender({
          nameList: [],
          dataList: [],
          timeList: []
        });
      }
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
}
